use std::hash::{DefaultHasher, Hash, Hasher};
use bincode;
use serde::{Deserialize, Serialize};
// use crypto::digest::Digest;
// use crypto::sha3::Sha3;
// use crypto::sha3::Sha3Mode::Sha3_256;

pub fn my_serilaze<T: ?Sized>(value: &T) -> Vec<u8>
    where T: Serialize
{
    let seirialize = bincode::serialize(value).unwrap();
    seirialize
}

pub fn my_derilaze<'a, T>(bytes: &'a [u8]) -> T
    where T: Deserialize<'a>
{
    let obj = bincode::deserialize(bytes).unwrap();
    obj
}




// 计算hash

pub fn get_hash<T:Hash + ?Sized>(value : &T) ->String {

    let mut s = DefaultHasher::new();
    value.hash(&mut s);
    s.finish().to_string()

}




#[cfg(test)]
mod test {
    use std::cmp::PartialEq;
    use serde::{Deserialize, Serialize};
    use crate::coder::{get_hash, my_derilaze, my_serilaze};

    #[derive(Serialize, Deserialize, Debug , PartialEq ,Eq)]
    struct Point {
        x: i32,
        y: i32,
    }

    #[test]
    fn test() {
        let p1 = Point { x: 2, y: 33 };
        let v1 = my_serilaze(&p1);
        println!("v1 is {:?}", v1);
        let obj: Point = my_derilaze(v1.as_slice());
        assert_eq!(p1, obj);

        let hash = get_hash(v1.as_slice()) ;

        // println!("hash is {}", hash);  // 8544948372876736123
        assert_eq!("8544948372876736123" , hash)

    }
}